'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DashboardLayout } from '@/components/layout/dashboard-layout';
import { AdminGuard } from '@/components/auth/PermissionGuard';
import { formatAddress, formatDate, formatCurrency } from '@/lib/utils';
import { multiChainApi } from '@/lib/multi-chain-api';
import { useChain } from '@/context/ChainContext';
import { Search, Activity, Pause, Play, Clock, TrendingUp, Calendar, BarChart3, Settings } from 'lucide-react';

interface Miner {
  id: string;
  user_id: string;
  wallet_address: string;
  miner_type: number;
  mining_mode: number;
  staked_amount: number;
  lock_start_time: string;
  lock_end_time: string;
  lock_period_days: number;
  is_active: boolean;
  last_claim_time?: string;
  start_tx_hash: string;
  start_block_number: number;
  created_at: string;
}

interface MinerStats {
  total_miners: number;
  active_miners: number;
  inactive_miners: number;
  total_staked: number;
  total_rewards_distributed: number;
  avg_lock_period: number;
  miners_distribution: {
    [minerType: string]: {
      活期: number;
      '30日': number;
      '90日': number;
      '180日': number;
      总计: number;
    };
  };
  period_totals: {
    活期: number;
    '30日': number;
    '90日': number;
    '180日': number;
    总计: number;
  };
}


export default function MinersPage() {
  const { t } = useTranslation('miners');
  const { currentChain } = useChain();
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all');
  const [minerTypeFilter, setMinerTypeFilter] = useState<'all' | 'M0' | 'M1' | 'M2' | 'M3' | 'M4' | 'M5' | 'M6'>('all');
  const [selectedMiner, setSelectedMiner] = useState<Miner | null>(null);

  // Fetch miner stats
  const { data: stats } = useQuery<MinerStats>({
    queryKey: ['miner-stats', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get('/api/v1/admin/miners/stats');
      return response.data;
    },
    refetchInterval: 30000,
  });

  // Fetch miners list
  const { data: miners, isLoading, refetch } = useQuery<Miner[]>({
    queryKey: ['miners', currentChain, searchTerm, statusFilter, minerTypeFilter],
    queryFn: async () => {
      const params = new URLSearchParams();
      params.append('limit', '200'); // Maximum allowed by backend
      if (searchTerm) params.append('search', searchTerm);
      if (statusFilter !== 'all') params.append('status', statusFilter);
      if (minerTypeFilter !== 'all') params.append('miner_type', minerTypeFilter.substring(1));
      
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(`/api/v1/admin/miners/all?${params}`);
      return response.data;
    },
    refetchInterval: 30000,
  });


  const handleToggleMiner = async (minerId: string, activate: boolean) => {
    try {
      const endpoint = activate ? 'activate' : 'deactivate';
      const client = multiChainApi.getClient(currentChain);
      await client.post(`/api/v1/admin/miners/${minerId}/${endpoint}`);
      refetch();
    } catch (error) {
      console.error('Error toggling miner status:', error);
    }
  };

  // Use API results directly since filtering is now done server-side
  const filteredMiners = miners || [];

  const getMinerTypeColor = (type: number) => {
    switch (type) {
      case 0: return 'bg-slate-100 text-slate-800';
      case 1: return 'bg-green-100 text-green-800';
      case 2: return 'bg-blue-100 text-blue-800';
      case 3: return 'bg-purple-100 text-purple-800';
      case 4: return 'bg-orange-100 text-orange-800';
      case 5: return 'bg-red-100 text-red-800';
      case 6: return 'bg-pink-100 text-pink-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getRemainingLockTime = (endTime: string) => {
    const now = new Date();
    const end = new Date(endTime);
    const diff = end.getTime() - now.getTime();
    
    if (diff <= 0) return t('list.unlocked');
    
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    if (days > 0) return `${days} ${t('list.days')}`;
    
    const hours = Math.floor(diff / (1000 * 60 * 60));
    return `${hours} ${t('list.hours')}`;
  };

  return (
    <DashboardLayout>
      <AdminGuard>
        <div className="space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold tracking-tight">{t('title')}</h1>
            <p className="text-muted-foreground">
              {t('subtitle')}
            </p>
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              onClick={() => router.push('/miner-config')}
              className="flex items-center gap-2"
              title="Configure miner type visibility for frontend DApp"
            >
              <Settings className="h-4 w-4" />
              Miner Types Config
            </Button>
          </div>
        </div>

        {/* Stats Cards */}
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-6">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{t('stats.totalMiners')}</CardTitle>
              <Activity className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats?.total_miners || 0}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{t('stats.activeMiners')}</CardTitle>
              <Play className="h-4 w-4 text-green-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-green-600">{stats?.active_miners || 0}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{t('stats.inactiveMiners')}</CardTitle>
              <Pause className="h-4 w-4 text-red-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-red-600">{stats?.inactive_miners || 0}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{t('stats.totalStaked')}</CardTitle>
              <TrendingUp className="h-4 w-4 text-blue-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatCurrency(stats?.total_staked || 0)}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{t('stats.rewardsDistributed')}</CardTitle>
              <TrendingUp className="h-4 w-4 text-purple-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatCurrency(stats?.total_rewards_distributed || 0)}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{t('stats.avgLockPeriod')}</CardTitle>
              <Clock className="h-4 w-4 text-orange-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats?.avg_lock_period || 0} {t('list.days')}</div>
            </CardContent>
          </Card>
        </div>

        {/* Miners Distribution Section */}
        {stats?.miners_distribution && (
          <div className="space-y-4">
            <div>
              <h2 className="text-xl font-semibold tracking-tight">{t('distribution.title')}</h2>
              <p className="text-muted-foreground">{t('distribution.subtitle')}</p>
            </div>
            
            {/* Period Totals Cards */}
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-5">
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">{t('distribution.periods.demand')}</CardTitle>
                  <Clock className="h-4 w-4 text-orange-600" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold text-orange-600">{stats.period_totals?.活期 || 0}</div>
                  <p className="text-xs text-muted-foreground">
                    {stats.period_totals?.总计 > 0 ? 
                      `${((stats.period_totals?.活期 || 0) / stats.period_totals.总计 * 100).toFixed(1)}%` : '0%'}
                  </p>
                </CardContent>
              </Card>
              
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">{t('distribution.periods.30days')}</CardTitle>
                  <Calendar className="h-4 w-4 text-blue-600" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold text-blue-600">{stats.period_totals?.['30日'] || 0}</div>
                  <p className="text-xs text-muted-foreground">
                    {stats.period_totals?.总计 > 0 ? 
                      `${((stats.period_totals?.['30日'] || 0) / stats.period_totals.总计 * 100).toFixed(1)}%` : '0%'}
                  </p>
                </CardContent>
              </Card>
              
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">{t('distribution.periods.90days')}</CardTitle>
                  <Calendar className="h-4 w-4 text-green-600" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold text-green-600">{stats.period_totals?.['90日'] || 0}</div>
                  <p className="text-xs text-muted-foreground">
                    {stats.period_totals?.总计 > 0 ? 
                      `${((stats.period_totals?.['90日'] || 0) / stats.period_totals.总计 * 100).toFixed(1)}%` : '0%'}
                  </p>
                </CardContent>
              </Card>
              
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">{t('distribution.periods.180days')}</CardTitle>
                  <Calendar className="h-4 w-4 text-purple-600" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold text-purple-600">{stats.period_totals?.['180日'] || 0}</div>
                  <p className="text-xs text-muted-foreground">
                    {stats.period_totals?.总计 > 0 ? 
                      `${((stats.period_totals?.['180日'] || 0) / stats.period_totals.总计 * 100).toFixed(1)}%` : '0%'}
                  </p>
                </CardContent>
              </Card>
              
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">{t('distribution.periods.total')}</CardTitle>
                  <BarChart3 className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{stats.period_totals?.总计 || 0}</div>
                  <p className="text-xs text-muted-foreground">{t('distribution.periods.allActiveMiner')}</p>
                </CardContent>
              </Card>
            </div>

            {/* Distribution Table */}
            <Card>
              <CardHeader>
                <CardTitle>{t('distribution.table.title')}</CardTitle>
                <CardDescription>
                  {t('distribution.table.description')}
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="overflow-x-auto">
                  <table className="w-full border-collapse">
                    <thead>
                      <tr className="border-b">
                        <th className="text-left py-3 px-4 font-medium">{t('distribution.table.minerType')}</th>
                        <th className="text-center py-3 px-4 font-medium">{t('distribution.periods.demand')}</th>
                        <th className="text-center py-3 px-4 font-medium">{t('distribution.periods.30days')}</th>
                        <th className="text-center py-3 px-4 font-medium">{t('distribution.periods.90days')}</th>
                        <th className="text-center py-3 px-4 font-medium">{t('distribution.periods.180days')}</th>
                        <th className="text-center py-3 px-4 font-medium">{t('distribution.periods.total')}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {Object.entries(stats.miners_distribution).map(([minerType, distribution]) => (
                        <tr key={minerType} className="border-b hover:bg-muted/50">
                          <td className="py-3 px-4">
                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getMinerTypeColor(parseInt(minerType.substring(1)))}`}>
                              {minerType}
                            </span>
                          </td>
                          <td className="text-center py-3 px-4 text-orange-600 font-medium">{distribution.活期}</td>
                          <td className="text-center py-3 px-4 text-blue-600 font-medium">{distribution['30日']}</td>
                          <td className="text-center py-3 px-4 text-green-600 font-medium">{distribution['90日']}</td>
                          <td className="text-center py-3 px-4 text-purple-600 font-medium">{distribution['180日']}</td>
                          <td className="text-center py-3 px-4 font-bold">{distribution.总计}</td>
                        </tr>
                      ))}
                      <tr className="border-b-2 border-primary bg-muted/30 font-bold">
                        <td className="py-3 px-4">{t('distribution.table.total')}</td>
                        <td className="text-center py-3 px-4 text-orange-600">{stats.period_totals?.活期 || 0}</td>
                        <td className="text-center py-3 px-4 text-blue-600">{stats.period_totals?.['30日'] || 0}</td>
                        <td className="text-center py-3 px-4 text-green-600">{stats.period_totals?.['90日'] || 0}</td>
                        <td className="text-center py-3 px-4 text-purple-600">{stats.period_totals?.['180日'] || 0}</td>
                        <td className="text-center py-3 px-4">{stats.period_totals?.总计 || 0}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </CardContent>
            </Card>
          </div>
        )}

        {/* Filters */}
        <Card>
          <CardHeader>
            <CardTitle>{t('list.title')}</CardTitle>
            <CardDescription>{t('list.subtitle')}</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex flex-col sm:flex-row gap-4 mb-6">
              <div className="flex-1 relative">
                <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                <input
                  type="text"
                  placeholder={t('list.searchPlaceholder')}
                  className="w-full pl-10 pr-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
              <div className="flex gap-2">
                <select
                  className="px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value as 'all' | 'active' | 'inactive')}
                >
                  <option value="all">{t('list.filters.allStatus')}</option>
                  <option value="active">{t('list.filters.active')}</option>
                  <option value="inactive">{t('list.filters.inactive')}</option>
                </select>
                <select
                  className="px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  value={minerTypeFilter}
                  onChange={(e) => setMinerTypeFilter(e.target.value as 'all' | 'M0' | 'M1' | 'M2' | 'M3' | 'M4' | 'M5' | 'M6')}
                >
                  <option value="all">{t('list.filters.allTypes')}</option>
                  <option value="M0">M0 Miners</option>
                  <option value="M1">{t('list.filters.m1Miners')}</option>
                  <option value="M2">{t('list.filters.m2Miners')}</option>
                  <option value="M3">{t('list.filters.m3Miners')}</option>
                  <option value="M4">M4 Miners</option>
                  <option value="M5">M5 Miners</option>
                  <option value="M6">M6 Miners</option>
                </select>
              </div>
            </div>

            {/* Miners Table */}
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b">
                    <th className="text-left p-4">{t('list.table.walletAddress')}</th>
                    <th className="text-left p-4">{t('list.table.type')}</th>
                    <th className="text-left p-4">{t('list.table.stakedAmount')}</th>
                    <th className="text-left p-4">{t('list.table.lockPeriod')}</th>
                    <th className="text-left p-4">{t('list.table.remainingTime')}</th>
                    <th className="text-left p-4">{t('list.table.status')}</th>
                    <th className="text-left p-4">{t('list.table.started')}</th>
                    <th className="text-left p-4">{t('list.table.actions')}</th>
                  </tr>
                </thead>
                <tbody>
                  {isLoading ? (
                    <tr>
                      <td colSpan={8} className="text-center p-8">
                        {t('list.loading')}
                      </td>
                    </tr>
                  ) : filteredMiners.length === 0 ? (
                    <tr>
                      <td colSpan={8} className="text-center p-8 text-muted-foreground">
                        {t('list.noResults')}
                      </td>
                    </tr>
                  ) : (
                    filteredMiners.map((miner) => (
                      <tr key={miner.id} className="border-b hover:bg-muted/50">
                        <td className="p-4">
                          <div className="font-mono text-sm">
                            {formatAddress(miner.wallet_address)}
                          </div>
                        </td>
                        <td className="p-4">
                          <span className={`px-2 py-1 rounded text-sm ${getMinerTypeColor(miner.miner_type)}`}>
                            M{miner.miner_type}
                          </span>
                        </td>
                        <td className="p-4 font-medium">{formatCurrency(miner.staked_amount)}</td>
                        <td className="p-4">{miner.lock_period_days} {t('list.days')}</td>
                        <td className="p-4">
                          <span className={`text-sm ${
                            getRemainingLockTime(miner.lock_end_time) === 'Unlocked' 
                              ? 'text-green-600' 
                              : 'text-orange-600'
                          }`}>
                            {getRemainingLockTime(miner.lock_end_time)}
                          </span>
                        </td>
                        <td className="p-4">
                          {miner.is_active ? (
                            <span className="bg-green-100 text-green-800 px-2 py-1 rounded text-sm">
                              {t('list.status.active')}
                            </span>
                          ) : (
                            <span className="bg-red-100 text-red-800 px-2 py-1 rounded text-sm">
                              {t('list.status.inactive')}
                            </span>
                          )}
                        </td>
                        <td className="p-4 text-sm text-muted-foreground">
                          {formatDate(miner.created_at)}
                        </td>
                        <td className="p-4">
                          <div className="flex items-center gap-2">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => setSelectedMiner(miner)}
                            >
                              {t('details.actions.view')}
                            </Button>
                            {miner.is_active ? (
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => handleToggleMiner(miner.id, false)}
                                className="text-red-600 hover:text-red-700"
                              >
                                <Pause className="h-3 w-3" />
                              </Button>
                            ) : (
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => handleToggleMiner(miner.id, true)}
                                className="text-green-600 hover:text-green-700"
                              >
                                <Play className="h-3 w-3" />
                              </Button>
                            )}
                          </div>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>

        {/* Miner Detail Modal */}
        {selectedMiner && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
            <Card className="w-full max-w-4xl max-h-[80vh] overflow-y-auto">
              <CardHeader>
                <CardTitle>{t('details.title')}</CardTitle>
                <CardDescription>
                  {formatAddress(selectedMiner.wallet_address)} - M{selectedMiner.miner_type}
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Miner Info */}
                <div className="grid grid-cols-2 lg:grid-cols-3 gap-4">
                  <div>
                    <label className="text-sm font-medium">{t('details.info.walletAddress')}</label>
                    <div className="font-mono text-sm break-all">
                      {selectedMiner.wallet_address}
                    </div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.info.minerType')}</label>
                    <div className="text-sm">M{selectedMiner.miner_type}</div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.info.miningMode')}</label>
                    <div className="text-sm">
                      {selectedMiner.mining_mode === 0 ? t('details.miningMode.staticPos') : t('details.miningMode.dynamic')}
                    </div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.info.stakedAmount')}</label>
                    <div className="text-sm font-medium">{formatCurrency(selectedMiner.staked_amount)}</div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.info.lockPeriod')}</label>
                    <div className="text-sm">{selectedMiner.lock_period_days} {t('list.days')}</div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.info.remainingTime')}</label>
                    <div className="text-sm">{getRemainingLockTime(selectedMiner.lock_end_time)}</div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.info.lockStart')}</label>
                    <div className="text-sm">{formatDate(selectedMiner.lock_start_time)}</div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.info.lockEnd')}</label>
                    <div className="text-sm">{formatDate(selectedMiner.lock_end_time)}</div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.info.status')}</label>
                    <div className="text-sm">
                      {selectedMiner.is_active ? t('list.status.active') : t('list.status.inactive')}
                    </div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.info.startTransaction')}</label>
                    <div className="font-mono text-xs break-all">
                      {selectedMiner.start_tx_hash}
                    </div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.info.startBlock')}</label>
                    <div className="text-sm">{selectedMiner.start_block_number}</div>
                  </div>
                  {selectedMiner.last_claim_time && (
                    <div>
                      <label className="text-sm font-medium">{t('details.info.lastClaim')}</label>
                      <div className="text-sm">{formatDate(selectedMiner.last_claim_time)}</div>
                    </div>
                  )}
                </div>


                <div className="flex justify-end gap-2 pt-4">
                  <Button variant="outline" onClick={() => setSelectedMiner(null)}>
                    {t('details.actions.close')}
                  </Button>
                  {selectedMiner.is_active ? (
                    <Button
                      onClick={() => {
                        handleToggleMiner(selectedMiner.id, false);
                        setSelectedMiner(null);
                      }}
                      variant="danger"
                    >
                      {t('details.actions.deactivateMiner')}
                    </Button>
                  ) : (
                    <Button
                      onClick={() => {
                        handleToggleMiner(selectedMiner.id, true);
                        setSelectedMiner(null);
                      }}
                      className="bg-green-600 hover:bg-green-700"
                    >
                      {t('details.actions.activateMiner')}
                    </Button>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>
        )}
        </div>
      </AdminGuard>
    </DashboardLayout>
  );
}